package com.zui.util;

import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

/**
 * 
 * @author Sam
 * 
 */
public class JQGridFilterConverter extends StrutsTypeConverter {

	private static final Logger LOG = LoggerFactory
			.getLogger(JQGridFilterConverter.class);
	public static final String format = "yyyy-MM-dd";

	public Object convertFromString(Map ctx, String[] values, Class arg2) {
		if (values[0] == null || values[0].trim().equals("")) {
			return null;
		}

		// "{\"groupOp\":\"AND\",\"rules\":[{\"field\":\"catalogName\",\"op\":\"bw\",\"data\":\"200\"}]},{\"field\":\"parentCatalog.catalogName\",\"op\":\"bw\",\"data\":\"11\"}]}"
		String filters = values[0];

		String[] filterArray = filters.split("[{}]");
		JQGridFilter jqFilter = new JQGridFilter();

		for (String filter : filterArray) {
			if (filter.contains("groupOp")) {
				jqFilter.setGroupOp(filters.substring(
						filters.indexOf("\"groupOp\":") + 11,
						filters.indexOf(",\"rules\"") - 1));
			} else if (filter.contains("field")) {
				String field = filter.substring(
						filter.indexOf("\"field\":") + 9,
						filter.indexOf("\"op\":") - 2);
				String op = filter.substring(filter.indexOf("\"op\":") + 6,
						filter.indexOf("\"data\":") - 2);
				String data = filter.substring(filter.indexOf("\"data\":") + 8,
						filter.lastIndexOf("\""));

				// if data is empty string, it won't be added.
				if ("".equals(data.trim()))
					continue;

				if (field.contains(".")) {// association query
					
					//field:"mother.name" generates: hierarchyFields=[mother],field=name
					String[] temFields = field.split("\\.");
					String[] hierarchyFields = new String[temFields.length-1];
					
					field = temFields[temFields.length-1];
					System.arraycopy(temFields, 0, hierarchyFields, 0, hierarchyFields.length);
					
					jqFilter.addRule(new JQGridFilterRule(hierarchyFields,
							field, op, data));
				} else
					jqFilter.addRule(new JQGridFilterRule(field, op, data));
			}
		}
		LOG.debug("A JQGridFilter object is converted: " + jqFilter.toString());
		return jqFilter;
	}

	public String convertToString(Map context, Object o) {
		if (o instanceof JQGridFilter) {
			return o.toString();
		}
		return "";
	}

}